package com.dayatang.android.Activity;

import java.util.concurrent.ExecutionException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;

import com.dayatang.android.Activity.Application.MyApplication;
import com.dayatang.android.Task.ServerAddressTask;
import com.dayatang.android.config.Config;

public class ServerInitActivity extends BaseActivity {

	private EditText serverAddressText;
	private String serverAddress;
	private String serverAddressOther;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.server_init_activity);

		InitThis();
	}

	private void InitThis() {
		serverAddressText = (EditText) findViewById(R.id.server_address_edit);
		ServerAddressExists();
		((Button) findViewById(R.id.server_testAddress_btn)).setOnClickListener(AddressBtnClicker);
	}

	private void ServerAddressExists() {
		SharedPreferences sharedPreferences = getSharedPreferences(Config.COMMONDATA, MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE);

		serverAddress = sharedPreferences.getString(Config.SERVERADDRESS, "");
		serverAddressOther = serverAddress; // 修改服务器地址

		if (getIntentType().equals(Config.INIT)) {
			if (!serverAddress.equals("")) {
				saveServerAddressToApplication();
			}
		} else if (getIntentType().equals(Config.SETTINGS)) {
			serverAddressText.setText(serverAddress);
		}
	}

	private String getIntentType() {
		Intent intent = getIntent();
		return intent.getStringExtra(Config.WHERE);
	}

	private void saveServerAddressToApplication() {
		MyApplication application = (MyApplication) this.getApplication();
		application.setServerAddress(serverAddress);
		GoLoginActivity();
	}

	private void GoLoginActivity() {
		Intent intent = new Intent(ServerInitActivity.this, LoginActivity.class);

		if (getIntentType().equals(Config.SETTINGS) && !serverAddressOther.equals(serverAddressText.getText().toString())) {
			intent.putExtra(Config.LOGOUT, Config.RESETSERVERADDRESS);
			deleteDatabase(Config.DBNAME);
		}
		startActivity(intent);
		finish();
	}

	OnClickListener AddressBtnClicker = new OnClickListener() {
		public void onClick(View v) {
			if (validate()) {
				serverAddress = serverAddressText.getText().toString();
				try {
					if (chkConnection()) {
						if (URLUtil.isNetworkUrl(serverAddress)) {
							String result = new ServerAddressTask(
									ServerInitActivity.this).execute(
									serverAddress + "/remote/index.action")
									.get();
							if (result.equals(Config.OK)) {
								ToastShow(getString(R.string.serverAddress_alert_success));
								saveServerAddress();
							} else if (result.equals(Config.SERVERDIE)) {
								ToastShow(getString(R.string.server_go_wrong));
							} else {
								ToastShow(getString(R.string.serverAddress_alert_addressError));
							}
						} else {
							ToastShow(getString(R.string.serverAddress_address_format_error));
						}
					} else {
						ToastShow(getString(R.string.network_no_connection));
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			}
		}
	};

	private boolean validate() {
		serverAddress = serverAddressText.getText().toString();
		if (serverAddress.equals("")) {
			ToastShow(getString(R.string.serverAddress_noNull));
			return false;
		} else if (serverAddress.length() < Config.EIGHT) {
			ToastShow(getString(R.string.serverAddress_alert_addressError));
			return false;
		}
		return true;
	}

	private void saveServerAddress() {
		SharedPreferences sharedPreferences = getSharedPreferences(
				Config.COMMONDATA, MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE);

		Editor editor = sharedPreferences.edit();
		editor.putString(Config.SERVERADDRESS, serverAddress);
		editor.commit();
		saveServerAddressToApplication();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}
}
